package com.tataben.retrofit;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * Retrofit 转换器
 * Created by dlilang on 2017/11/7 0007.
 */
public class DLConverterFactory extends Converter.Factory {

    private final Gson gson;

    private DLConverterFactory(Gson gson) {
        this.gson = gson;
    }

    public static DLConverterFactory create() {
        return new DLConverterFactory(new Gson());
    }

    /**
     * HTTP 响应调用此方法
     * @param type
     * @param annotations
     * @param retrofit
     * @return
     */
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return new DLResponseConverter<>(gson, gson.getAdapter(TypeToken.get(type)));
    }

    /**
     * 有 @Body, @Part, @PartMap 注解时会调用此方法
     * @param type
     * @param parameterAnnotations
     * @param methodAnnotations
     * @param retrofit
     * @return
     */
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        boolean isJson = !(type == String.class
                || type == boolean.class || type == Boolean.class
                || type == byte.class || type == Byte.class
                || type == char.class || type == Character.class
                || type == double.class || type == Double.class
                || type == float.class || type == Float.class
                || type == int.class || type == Integer.class
                || type == long.class || type == Long.class
                || type == short.class || type == Short.class);
        return new DLBodyRequestConverter<>(gson, isJson, gson.getAdapter(TypeToken.get(type)));
    }

    /**
     * 有 @Field, @FieldMap, @Header, @HeaderMap, @Path, @Query, @QueryMap 注解时会调用此方法
     * @param type
     * @param annotations
     * @param retrofit
     * @return
     */
    public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return new DLJsonRequestConverter<>(gson, gson.getAdapter(TypeToken.get(type)));
    }
}